<template>
  <div class="app-container">
    <div v-show="!visibleDetails">
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      ></page-filter>
      <NewPageFilter :filter-btn="filterInfo.btnList"> </NewPageFilter>

      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="pageList"
        :check-box="false"
        :tab-index="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
      >
      </table-container>
    </div>
    <!-- 新增修改弹窗 -->
    <page-dialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title[dialogInfo.type]"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
        <template v-slot:form-useDeptNames>
          <el-input
            v-model="formInfo.data.useDeptNames"
            class="not-br not-mongolia"
            type="input"
            :disabled="true"
            placeholder="请选择部门"
          >
            <template #append>
              <el-icon @click="openDeptList"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
    </page-dialog>
    <!--部门选择框-->
    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :checkedList="selectDeptInfo.checkedList"
      :check-box="true"
      :highlight-row="false"
      :query="selectDeptInfo.query"
      :save-empty="true"
      @callback="selectDeptCallBack"
    />
  </div>
</template>

<script setup name="reportTemplateList">
import {
  addTemplate,
  updateTemplate,
  restoreTpl,
  pageList,
  loadReportProviders,
} from '@/api/report.js'
import { ElMessageBox } from 'element-plus'
const { proxy } = getCurrentInstance()
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
  },
  list: [
    {
      type: 'input',
      label: '模板名称/模板code/报表名称',
      value: 'keywords',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('report:template:add'),
      event: create,
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '模板名称',
      value: 'tplName',
    },
    {
      label: '模板Code',
      value: 'tplCode',
    },
    {
      label: '报表名称',
      value: 'ureportName',
    },
    {
      label: '使用部门',
      value: 'useDeptNames',
    },
    {
      label: '缺省值',
      value: 'defaultUreportName',
    },
    {
      label: '创建人',
      value: 'createBy',
    },
    {
      label: '备注',
      value: 'remark',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '190',
    btList: [
      {
        label: '修改',
        type: 'button',
        event: update,
        show: proxy.$permission('report:template:update'),
      },
      {
        label: '恢复缺省',
        type: 'button',
        event: recover,
        show: proxy.$permission('report:template:recover'),
      },
    ],
  },
})
const listTypeInfo = ref({
  reportList: [],
})
// 表单相关
const formInfo = ref({
  ref: null,
  data: {
    tplName: '',
    tplCode: '',
    ureportName: '',
    useDeptIds: '',
  },
  fieldList: [
    {
      label: '模板名称',
      value: 'tplName',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '模板Code',
      value: 'tplCode',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '报表名称',
      value: 'ureportName',
      type: 'select',
      list: 'reportList',
      filterable: true,
    },
    {
      label: '使用部门',
      value: 'useDeptNames',
      type: 'slot',
      required: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 500,
    },
  ],
  rules: {
    tplName: [{ required: true, message: '请输入编码名称', trigger: 'blur' }],
    tplCode: [{ required: true, message: '请选择编码类型', trigger: 'blur' }],
    ureportName: [
      { required: true, message: '请选择报表名称', trigger: 'blur' },
    ],
    //useDeptNames: [{ required: true, message: '请选择使用部门', trigger: 'blur' }],
  },
  labelWidth: '100px',
})

// 弹窗相关
const dialogInfo = ref({
  title: {
    create: '添加',
    update: '修改',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: save,
      saveLoading: false,
      show: true,
    },
  ],
})

onMounted(() => {
  getReportProviders()
  //getList()
})
onActivated(() => {
  getReportProviders()
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
function openDeptList() {
  selectDeptInfo.value.visible = true
}
function selectDeptCallBack(row) {
  console.log(row, 66)
  if (row && row.length) {
    let ids = row.map((item) => item.id)
    let names = row.map((item) => item.name)
    formInfo.value.data['useDeptIds'] = ids
    formInfo.value.data['useDeptNames'] = names.toString()
  } else {
    formInfo.value.data['useDeptIds'] = ''
    formInfo.value.data['useDeptNames'] = ''
  }
}
async function getReportProviders() {
  const res = await loadReportProviders()
  res.data.forEach((element) => {
    element.key = element.name
    element.value = element.name
  })
  listTypeInfo.value.reportList = res.data
}

function close() {
  dialogInfo.value.visible = false
  formInfo.value.data = {}
}

// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}

// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}

function save() {
  const _dialogInfo = dialogInfo.value
  const _tableInfo = tableInfo.value
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let api
      const params = formInfo.value.data
      const type = dialogInfo.value.type
      if (type === 'create') {
        api = addTemplate
      } else if (type === 'update') {
        api = updateTemplate
      } else {
        return
      }
      _dialogInfo.btLoading = true
      if (!params.useDeptIds) {
        delete params.useDeptIds
        delete params.useDeptNames
      }
      if (params.useDeptIds && !Array.isArray(params.useDeptIds)) {
        params.useDeptIds = params.useDeptIds.split(',')
      }
      api(params)
        .then((res) => {
          if (res.success) {
            _dialogInfo.visible = false
            _tableInfo.refresh = Math.random()
          }
          _dialogInfo.btLoading = false
        })
        .catch((e) => {
          _dialogInfo.btLoading = false
        })
    }
  })
}

// 创建
function create() {
  formInfo.value.data = {}
  selectDeptInfo.value.checkedList = []
  dialogInfo.value.type = 'create'
  dialogInfo.value.visible = true
}

// 编辑
function update(data) {
  dialogInfo.value.type = 'update'
  if (data.hasOwnProperty('useDeptIds')) {
    selectDeptInfo.value.checkedList = data.useDeptIds
      .split(',')
      .map((item) => Number(item))
  } else {
    selectDeptInfo.value.checkedList = []
  }
  dialogInfo.value.visible = true
  // 显示信息
  formInfo.value.data = { ...data }
}

/**恢复确认 */
async function recover(row) {
  let str = `是否重置模板名称为【${row.tplName}】的数据项?`
  if (row.defaultUreportName) {
    str = `是否将模板名称为【${row.tplName}】的数据项重置为【${row.defaultUreportName}】?`
  }
  const ok = await ElMessageBox.confirm(str)
  if (ok) {
    const res = await restoreTpl(row.id)
    if (res.data) {
      proxy.$message.success('重置成功')
      search()
    }
  }
}

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    // 对表格获取到的数据做处理
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
</script>

<style scoped></style>
